package com.heima.user.gateway.filter;

import com.heima.user.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author 86155
 */
@Component
@Order(-1)
@Slf4j
public class AuthFilter implements GlobalFilter {

    //注入nacos中的ignoreUrl的信息
    @Value("${ignoreUrl}")
    private List<String> ignoreUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("过滤器执行了");
        //1.获取执行前与执行后的结果
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断是否为登录请求，是的话放行
        String path = request.getURI().getPath();
        if (path.contains("login")) {
            log.info("登录请求，放行");
            return chain.filter(exchange);
        }
        //3.判断token是否为空，为空则返回异常401
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            log.info("token为空，不能执行了");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.token不为空则解析token 判断token是否过期， 过期则返回401
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int flag = AppJwtUtil.verifyToken(claimsBody);
        if (flag == 1 || flag == 2) {
            log.info("token过期了");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }
}
